package com.tensquare.user.controller;
import java.util.*;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tensquare.user.vo.UserVo;
import org.aspectj.weaver.patterns.IToken;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.tensquare.user.pojo.User;
import com.tensquare.user.service.UserService;

import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.web.client.RestTemplate;
import util.IdWorker;
import util.JwtUtil;

/**
 * 控制器层
 * @author Administrator
 *
 */
@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;

	@Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	private IdWorker idWorker;

	@Autowired
	private  JwtUtil jwtUtil;



	/**
	 * 更新好友粉丝数和用户关注数
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/{userid}/{friendid}/{x}",method = RequestMethod.PUT)
	public void updateFansCountAndFollowCount(@PathVariable String userid,@PathVariable String friendid,@PathVariable int x){

		userService.updateFansCountAndFollowCount(x,userid,friendid);
	}


	@RequestMapping(value = "/login",method = RequestMethod.POST)
	public Result login(@RequestBody User user){

		user = userService.login(user.getUsername(),user.getPassword());
		if(user == null){

			return new Result(false,StatusCode.LOGINERROR,"登录失败");

		}
		
		String token = jwtUtil.createJWT(user.getId(),user.getMobile(),"user");
		Map<String,Object> map = new HashMap<>();
		map.put("token", token);
		map.put("roles","user");
		UserVo userVo = new UserVo();
		BeanUtils.copyProperties(user,userVo);
		map.put("userinfo",userVo);
		return new Result(true,StatusCode.OK,"登录成功",map);

	}

	/**
	 * 手机快捷登录
	 * @param code
	 * @param user
	 * @return
	 */
	@RequestMapping(value="/phonelogin/{code}",method = RequestMethod.POST)
	public Result loginByPhone(@PathVariable String code,@RequestBody User user){

		//得到缓存中的验证码
		String checkCodeRedis = (String) redisTemplate.opsForValue().get("checkCode_"+user.getMobile());
		if(checkCodeRedis == null || checkCodeRedis.equals("")){
			return new Result(false,StatusCode.ERROR,"请先获取手机验证码");
		}
		if(!checkCodeRedis.equals(code)){
			return new Result(false,StatusCode.ERROR,"请输入正确的验证码");
		}
		User userCheck = userService.findByPhone(user.getMobile());
		String id = "";
		if(userCheck == null ){
			id = userService.addByPhone(user);
			if(id == null || id.equals("")){
				return new Result(false,StatusCode.ERROR,"注册失败！");
			}

		}else{
			id = userCheck.getId();
		}
		String token = jwtUtil.createJWT(id,user.getMobile(),"user");
		Map<String,Object> map = new HashMap<>();
		map.put("token", token);
		map.put("roles","user");
		UserVo userVo = new UserVo();
		user.setId(id);
		BeanUtils.copyProperties(user,userVo);
		map.put("userinfo",userVo);
		return new Result(true,StatusCode.OK,"登录成功",map);
	}


	/**
	 * 发送短信验证码
	 *
	 */
	@RequestMapping(value="/sendsms/{mobile}",method = RequestMethod.POST)
	public Result sendSms(@PathVariable String mobile){

		userService.sendSms(mobile);
		return new Result(true,StatusCode.OK,"发送成功");

	}

	/**
	 * 用户注册
	 * @return
	 */
	@RequestMapping(value="/register/{code}",method = RequestMethod.POST)
	public Result regist(@PathVariable String code ,@RequestBody User user){

		//得到缓存中的验证码
		String checkCodeRedis = (String) redisTemplate.opsForValue().get("checkCode_"+user.getMobile());
		if(checkCodeRedis == null || checkCodeRedis.equals("")){
			return new Result(false,StatusCode.ERROR,"请先获取手机验证码");
		}
		if(!checkCodeRedis.equals(code)){
			return new Result(false,StatusCode.ERROR,"请输入正确的验证码");
		}
		User userCheckUsername = userService.findByUsername(user.getUsername());
		if(userCheckUsername != null){
			return new Result(false,StatusCode.ERROR,"该用户名已存在");
		}


		User userCheck = userService.findByPhone(user.getMobile());
		String id = "";
		if(userCheck == null ){
			id = userService.add(user);
			if(id == null || id.equals("")){
				return new Result(false,StatusCode.ERROR,"注册失败");
			}
		}else{

				if(userCheck.getUsername()!=null){
					return new Result(false,StatusCode.ERROR,"该手机已注册账号！");
			}
			userCheck.setPassword(user.getPassword());
			userCheck.setUsername(user.getUsername());
			userService.update(userCheck);
		}


		return new Result(true,StatusCode.OK,"注册成功");

	}

	@RequestMapping(value="/checkUsername",method = RequestMethod.POST)
	public Result checkUsername(@RequestBody User user){


		User userCheck = userService.findByUsername(user.getUsername());

		if(userCheck == null ){
			return new Result(true,StatusCode.OK,"用户名可用");
		}else{
			return new Result(false,StatusCode.ERROR,"用户名已存在");
		}

	}

	@RequestMapping(value="/checkPhone",method = RequestMethod.POST)
	public Result checkPhone(@RequestBody User user){


		User userCheck = userService.findByPhone(user.getMobile());

		if(userCheck == null ){
			return new Result(true,StatusCode.OK,"手机号可用");
		}else{
			if(userCheck.getUsername() != null){
				return new Result(false,StatusCode.ERROR,"该手机号已注册账号");
			}
			return new Result(true,StatusCode.OK,"手机号可用");

		}



	}




	/**
	 * 查询全部数据
	 * @return
	 */
	@RequestMapping(method= RequestMethod.GET)
	public Result findAll(){
		return new Result(true,StatusCode.OK,"查询成功",userService.findAll());
	}
	
	/**
	 * 根据ID查询
	 * @param id ID
	 * @return
	 */
	@RequestMapping(value="/{id}",method= RequestMethod.GET)
	public Result findById(@PathVariable String id){
		return new Result(true,StatusCode.OK,"查询成功",userService.findById(id));
	}


	/**
	 * 分页+多条件查询
	 * @param searchMap 查询条件封装
	 * @param page 页码
	 * @param size 页大小
	 * @return 分页结果
	 */
	@RequestMapping(value="/search/{page}/{size}",method=RequestMethod.POST)
	public Result findSearch(@RequestBody Map searchMap , @PathVariable int page, @PathVariable int size){
		Page<User> pageList = userService.findSearch(searchMap, page, size);
		return  new Result(true,StatusCode.OK,"查询成功",  new PageResult<User>(pageList.getTotalElements(), pageList.getContent()) );
	}


	/**
     * 根据条件查询
     * @param searchMap
     * @return
     */
    @RequestMapping(value="/search",method = RequestMethod.POST)
    public Result findSearch( @RequestBody Map searchMap){
        return new Result(true,StatusCode.OK,"查询成功",userService.findSearch(searchMap));
    }
	
	/**
	 * 增加
	 * @param user
	 */
	@RequestMapping(method=RequestMethod.POST)
	public Result add(@RequestBody User user  ){
		userService.add(user);
		return new Result(true,StatusCode.OK,"增加成功");
	}
	
	/**
	 * 修改
	 * @param user
	 */
	@RequestMapping(value="/update",method= RequestMethod.PUT)
	public Result update(@RequestBody User user){
		System.out.println(user.getStatus());
		userService.updateStatus(user);
		return new Result(true,StatusCode.OK,"修改成功");
	}

	@RequestMapping(value="/updateUserinfo",method= RequestMethod.PUT)
	public Result updateUserinfo(@RequestBody User user){
		System.out.println(user.getStatus());
		userService.updateUserinfo(user);
		return new Result(true,StatusCode.OK,"修改成功");
	}

	
	/**
	 * 删除 必须有admin角色才可以删除
	 * @param id
	 */
	@RequestMapping(value="/delete/{id}",method= RequestMethod.DELETE)
	public Result delete(@PathVariable String id ){
		System.out.println(id);
		userService.deleteById(id);
		return new Result(true,StatusCode.OK,"删除成功");
	}



	
}
